//
//  CPointUtil.cpp
//  NinjaTurtle
//
//  Created by Nguyen Tri Chung on 1/30/15.
//
//

#include "CPointUtil.h"

bool CPointUtil::isPointInRectangle(Point point, Point rectPosition, float width, float height) {
    float x1 = rectPosition.x - width / 2;
    float x2 = rectPosition.x + width / 2;
    float y1 = rectPosition.y - height / 2;
    float y2 = rectPosition.y + height / 2;
    return ((x1 <= point.x) && (point.x <= x2) && (y1 <= point.y) && (point.y <= y2));
}

void CPointUtil::checkLimit(RectBody* owner, RectBody* target, TouchDirection& touchDirection, float& limitValue) {
    limitValue = -9999;
    if (CPointUtil::b2Interact(owner, target)) {
        float ownerWidth = owner->getWidth();
        float ownerHeight = owner->getHeight();
        
        float minX = target->getPosition().x - target->getWidth() / 2 - ownerWidth / 2;
        float maxX = target->getPosition().x + target->getWidth() / 2 + ownerWidth / 2;
        float minY = target->getPosition().y - target->getHeight() / 2 - ownerHeight / 2;
        float maxY = target->getPosition().y + target->getHeight() / 2 + ownerHeight / 2;
        
        float touchLeft = abs(owner->getPosition().x - minX);
        float touchRight = abs(owner->getPosition().x - maxX);
        float touchUp = abs(owner->getPosition().y - maxY);
        float touchDown = abs(owner->getPosition().y - minY);
        
        touchDirection = TOUCH_NONE;
        
        if (touchLeft < touchRight &&
            touchLeft < touchUp &&
            touchLeft < touchDown) {

            limitValue = minX;
            touchDirection = TOUCH_LEFT;
        }
        
        if (touchRight < touchUp &&
            touchRight < touchLeft &&
            touchRight < touchDown) {
            
            limitValue = maxX;
            touchDirection = TOUCH_RIGHT;
        }
        
        if (touchUp < touchRight &&
            touchUp < touchLeft &&
            touchUp < touchDown) {
            
            limitValue = maxY;
            touchDirection = TOUCH_UP;
        }
        
        if (touchDown < touchRight &&
            touchDown < touchLeft &&
            touchDown < touchUp) {
            
            limitValue = minY;
            touchDirection = TOUCH_DOWN;
        }
    } else {
        touchDirection = TOUCH_NONE;
    }
}

bool CPointUtil::b2Interact(RectBody* body1, RectBody* body2) {
    Rect rect1, rect2;
    rect1.setRect(body1->getPosition().x - body1->getWidth() / 2, body1->getPosition().y - body1->getHeight() / 2, body1->getWidth(), body1->getHeight());
    rect2.setRect(body2->getPosition().x - body2->getWidth() / 2, body2->getPosition().y - body2->getHeight() / 2, body2->getWidth(), body2->getHeight());
    return rect1.intersectsRect(rect2);
}